package com.baidu.springcloud.controller;

import com.baidu.springcloud.bean.Payment;
import com.baidu.springcloud.common.CommonResult;
import com.baidu.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author ShiLei
 * @version v1.0
 * @date 2020-03-11 15:11
 */
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("api/order")
public class OrderController {

    /**
     * 服务注册中心的服务名称代替 ip地址以及端口号 以达到负载均衡机制
     */
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/api/payment/";
//    private static final String PAYMENT_URL = "http://localhost:8001/api/payment/";

    /**
     * 将注入配置中的restTemplate注入进行远程调用
     */
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 调用8001服务的创建接口
     *
     * @param payment 参数
     * @return 返回结果
     */
    @GetMapping("save")
    public CommonResult save(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "save", payment, CommonResult.class);
    }

    /**
     * 调用8001服务的查询接口
     *
     * @param id id
     * @return 返回结果
     */
    @GetMapping("getPaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "getPaymentById/" + id, CommonResult.class);
    }

    /**
     * 自定义负载均衡算法轮询访问服务器
     *
     * @return 返回服务器端口
     */
    @GetMapping(value = "lb")
    public String getPaymentUrl() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (null == instances || instances.size() <= 0) {
            return "服务器为空";
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/api/payment/lb", String.class);

    }

    @GetMapping("consumer/zipkin")
    public String consumer() {
        return restTemplate.getForObject("http://localhost:8001" + "/api/payment/zipkin", String.class);
    }
}
